package com.xs.shop.content.service.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xs.shop.common.exceptions.BusinessException;
import com.xs.shop.common.exceptions.enums.Resp;
import com.xs.shop.content.model.entity.DocCategory;
import com.xs.shop.content.service.mapper.DocCategoryMapper;
import com.xs.shop.content.service.service.DocCategoryService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * <p>
 *  文档分类服务实现类
 * </p>
 *
 * @author xs
 * @since 2025-07-16
 */
@Service
public class DocCategoryServiceImpl extends ServiceImpl<DocCategoryMapper, DocCategory> implements DocCategoryService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DocCategory addCategory(DocCategory docCategory) {
        // 设置业务默认值
        if (docCategory.getIsShow() == null) {
            docCategory.setIsShow((byte) 1); // 默认显示
        }
        if (docCategory.getSort() == null) {
            docCategory.setSort(0); // 默认排序值
        }
        
        // 保存分类
        this.save(docCategory);
        return docCategory;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteCategory(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        
        return this.removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DocCategory updateCategory(DocCategory docCategory) {
        if (docCategory == null || docCategory.getId() == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        
        this.updateById(docCategory);
        return docCategory;
    }

    @Override
    public DocCategory getCategoryById(Long id) {
        if (id == null) {
            throw new BusinessException(Resp.INVALID_PARAM);
        }
        
        return this.getById(id);
    }

    @Override
    public Page<DocCategory> pageCategory(Integer current,Integer pageSize, String name, Byte isShow) {
        LambdaQueryWrapper<DocCategory> queryWrapper = new LambdaQueryWrapper<>();
        
        // 按名称模糊查询
        if (StringUtils.hasText(name)) {
            queryWrapper.like(DocCategory::getName, name);
        }
        
        // 按显示状态查询
        if (isShow != null) {
            queryWrapper.eq(DocCategory::getIsShow, isShow);
        }
        
        // 按排序字段排序
        queryWrapper.orderByAsc(DocCategory::getSort);
        
        return this.page(new Page<>(current,pageSize), queryWrapper);
    }
}
